package com.csun.cmny.provider.controller;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.pojo.ExpCtrItem;
import com.csun.cmny.provider.pojo.SetMeal;
import com.csun.cmny.provider.pojo.SetMealExpItem;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.ExpCtrItemService;
import com.csun.cmny.provider.service.OldmanCheckInService;
import com.csun.cmny.provider.service.SetMealService;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 * 套餐管理
 * */
@RestController
@RequestMapping("/SetMeal")
public class SetMealController extends BaseController {

    @Autowired
    private SetMealService setMealService;

    @Autowired
    private ExpCtrItemService expCtrItemService;

    @Resource
    private OldmanCheckInService oldmanCheckInService;

    @Resource
    private CmnyMessageSource cmnyMessageSource;



    /*
     * 这里的认证和当前登录的用户注解先预留，等完善了再进行修改
     * 1.判断该用户是否属于该机构人员
     * */
    //添加套餐
    @RequestMapping(value = "/addSetMeal", method = RequestMethod.POST)
    public Wrapper addSetMeal(@RequestBody SetMeal setMeal) {
        //对于设置的折扣没有进行校验，目前需求没有明确，不确定是在总价设置折扣还是每个项目设置折扣
        //如果是总价设置折扣，这里必须对折扣进行校验；如果是每个项目设置折扣，那必须对每个项目的折扣进行校验
        //校验
        if (StringUtils.isEmpty(setMeal.getSetMealName())) {
            //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"套餐名称不能为空",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.name.null", null));
        }
        if (setMeal.getBeforeDis() == null) {
            //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"套餐折前总价不能为空",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.discount.before", null));
        }
        if (setMeal.getAfterDis() == null) {
            //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"套餐折后总价不能为空",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.later", null));
        }
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        //判断该套餐名称是否已经在该社区中存在
        SetMeal setMeal1 = new SetMeal();
        setMeal1.setSetMealName(setMeal.getSetMealName());
        setMeal1.setHomeId(homeId);
        SetMeal setMeal2 = setMealService.selectBySetMeal(setMeal1);
        if (setMeal2 != null) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该名称的套餐已经在该社区中存在",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.name.error", null));
        }
        //插入套餐
        setMeal.setHomeId(homeId);
        setMeal.setIsEdit(0);
        int n = setMealService.insert(setMeal);
        if (n <= 0) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"添加失败",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("Examine.add.fail", null));
        }
        int m = 0;
        //判断套餐里面的项目集合是否为空
        List<SetMealExpItem> setMealExpItemList = setMeal.getSetMealExpItemList();
        //项目集合——用于修改被套餐使用的项目的isDelete，当isDelete为0时表示该项目可以被删除
        List<ExpCtrItem> expCtrItemList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(setMealExpItemList)) {
            for (int i = 0; i <setMealExpItemList.size() ; i++) {
                SetMealExpItem setMealExpItem = setMealExpItemList.get(i);
                //校验
               /* if (setMealExpItem.getAfterDis() == null) {
                    return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目折后价格不能为空",null);
                }
                if (setMealExpItem.getDays() == null) {
                    return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目天数不能为空",null);
                }*/
                if (setMealExpItem.getItemId() == null) {
                    //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目id不能为空",null);
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("ExpenseItem.id.null", null));
                }
              /*  if (setMealExpItem.getDiscount() == null) {
                    return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"折扣不能为空",null);
                }*/
                //设置套餐id
                setMealExpItem.setSetMealId(setMeal.getSetMealId());
                //获取当前登录用户的id
                setMealExpItem.setModifier(1L);
                //项目对象——用于存储对象信息
                ExpCtrItem expCtrItem = new ExpCtrItem();
                expCtrItem.setItemId(setMealExpItem.getItemId());
                expCtrItemList.add(expCtrItem);
            }
            //批量修改项目isDelete值，自动加一
            int a = expCtrItemService.updateBatch(expCtrItemList);
            if (a <= 0) {
                System.out.println("********************新增套餐时修改项目isDelete自加一失败********************");
            }
            //批量插入关系表
            m = setMealService.insertBatch(setMealExpItemList);
        }
        if (m <= 0) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"套餐添加成功,但是添加项目失败",m);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"添加成功",n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }
    //根据id删除套餐
    @RequestMapping(value = "/delSetMealById", method = RequestMethod.POST)
    public Wrapper delSetMealById(Integer setMealId) {
        if (setMealId == null) {
            //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"套餐id不能为空",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.id.null", null));
        }

        //判断当前套餐是否被已入院，待评估，待缴费状态的老人使用
        List<Map<String, Object>> isUsed = setMealService.isMealBeUsed(setMealId,getLoginAuthDto().getGroupId().intValue());
        if(isUsed.size()>0){
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该套餐被老人使用中,不能修改或删除该套餐",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.man.del", null));
        }

        int count = oldmanCheckInService.selectCountBySetMealId(setMealId);
        if (count > 0) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该套餐被老人使用中,不能删除",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.man.del", null));
        }

        SetMealExpItem setMealExpItem = new SetMealExpItem();
        setMealExpItem.setSetMealId(setMealId);

    /*   //查询该套餐下的所有项目id  2019-01-11前
        SetMeal setMeal2 = setMealService.selectById(setMealId);
        List<SetMealExpItem> setMealExpItemList = setMeal2.getSetMealExpItemList();
        if (!CollectionUtils.isEmpty(setMealExpItemList)) {
            //项目id集合
            List<ExpCtrItem> expCtrItemList = new ArrayList<>();
            for (int i = 0; i <setMealExpItemList.size() ; i++) {
                ExpCtrItem expCtrItem = new ExpCtrItem();
                expCtrItem.setItemId(setMealExpItemList.get(i).getItemId());
            }
            //删除前现先将套餐下每个项目的isDelete减一
            int a = expCtrItemService.updateBatchSub(expCtrItemList);
            if (a <= 0) {
                System.out.println("********************新增套餐时修改项目isDelete自减一失败********************");
            }
        }*/

        //2019-01-11后 update by huangxm
        List<SetMealExpItem> bySetMealId = setMealService.findBySetMealId(setMealId);
        if (!CollectionUtils.isEmpty(bySetMealId)){
            List<ExpCtrItem> expCtrItemList = new ArrayList<>();
            for (int i = 0; i <bySetMealId.size() ; i++) {
                ExpCtrItem expCtrItem = new ExpCtrItem();
                expCtrItem.setItemId(bySetMealId.get(i).getItemId());
                expCtrItemList.add(expCtrItem);
            }
            int a = expCtrItemService.updateBatchSub(expCtrItemList);
            if (a <= 0) {
                System.out.println("********************新增套餐时修改项目isDelete自减一失败********************");
            }
        }


        //删除关系表数据
        int n = setMealService.deleteBySetMealExpItem(setMealExpItem);
        //删除套餐
        int m = setMealService.deleteById(setMealId);
        if (m <= 0) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"没有此id",setMealId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("Examine.not.id", null));
        }
        //return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"删除成功",n);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }

    //修改套餐
    @RequestMapping(value = "/updateSetMeal", method = RequestMethod.POST)
    public Wrapper updateSetMeal(@RequestBody SetMeal setMeal){
        //校验
        if (setMeal.getSetMealId() == null) {
            //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"套餐id不能为空",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.id.null", null));
        }
        //获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        //判断当前套餐是否被已入院，待评估，待缴费状态的老人使用
        List<Map<String, Object>> isUsed = setMealService.isMealBeUsed(setMeal.getSetMealId(),homeId);
        if(isUsed.size()>0){
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该套餐被老人使用中,不能修改或删除该套餐",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.man.del", null));
        }

        // 判断老人入院是否使用该套餐
        int count = oldmanCheckInService.selectCountBySetMealId(setMeal.getSetMealId());
        if (count > 0) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该套餐被老人使用中,不能修改",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.man.del", null));
        }

        // 判断老人护理是否使用该套餐


        //判断该套餐名称是否已经在该社区中存在
        SetMeal setMealQuery = new SetMeal();
        setMealQuery.setSetMealName(setMeal.getSetMealName());
        setMealQuery.setHomeId(homeId);
        SetMeal setMeal2 = setMealService.selectBySetMeal(setMealQuery);
        if (setMeal2 != null && !setMeal2.getSetMealId().equals(setMeal.getSetMealId())) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该名称的套餐已经在该社区中存在",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.name.error", null));
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(setMeal.getSetMealName())) {
            SetMeal setMeal3 = new SetMeal();
            setMeal3.setSetMealName(setMeal.getSetMealName());
            setMeal3.setHomeId(homeId);
            int a = setMealService.updateById(setMeal);
            if (a <= 0) {
                //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"修改失败",null);
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                        .getMessage("Examine.del.fail", null));
            }
        }
        List<SetMealExpItem> setMealExpItemList = setMeal.getSetMealExpItemList();
        int m = -1;
        if (!CollectionUtils.isEmpty(setMealExpItemList)) {
            SetMeal setMeal1 = new SetMeal();
            setMeal1.setSetMealId(setMeal.getSetMealId());
            //将该套餐初始选择的项目的isDelete进行自减一
            SetMeal setMeal3 = setMealService.selectById(setMeal.getSetMealId());
            List<SetMealExpItem> setMealExpItemList1 = setMeal3.getSetMealExpItemList();
            if (!CollectionUtils.isEmpty(setMealExpItemList1)) {
                //项目id自减集合
                List<ExpCtrItem> expCtrItemList = new ArrayList<>();
                for (int i = 0; i <setMealExpItemList1.size() ; i++) {
                    ExpCtrItem expCtrItem = new ExpCtrItem();
                    expCtrItem.setItemId(setMealExpItemList1.get(i).getItemId());
                }
                //项目的isDelete值进行减一
                int a = expCtrItemService.updateBatchSub(expCtrItemList);
                if (a <= 0) {
                    System.out.println("********************修改套餐时修改项目isDelete自减一失败********************");
                }
            }
            //项目id自增集合
            List<ExpCtrItem>  expCtrItemList1 = new ArrayList<>();
            for (int i = 0; i <setMealExpItemList.size() ; i++) {
                SetMealExpItem setMealExpItem = setMealExpItemList.get(i);
                //校验
                if (setMealExpItem.getAfterDis() == null) {
                    //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目折后价格不能为空",null);
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("ExpenseType.before.null", null));
                }
                if (setMealExpItem.getDays() == null) {
                    //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目天数不能为空",null);
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("ExpenseType.day.null", null));
                }
                if (setMealExpItem.getItemId() == null) {
                    //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目id不能为空",null);
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("ExpenseItem.id.null", null));
                }
                if (setMealExpItem.getDiscount() == null) {
                    //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"折扣不能为空",null);
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                            .getMessage("ExpenseType.dis.null", null));
                }
                //设置套餐id
                setMealExpItem.setSetMealId(setMeal.getSetMealId());
                //获取当前登录用户的id
                setMealExpItem.setModifier(1L);
                ExpCtrItem expCtrItem = new ExpCtrItem();
                expCtrItem.setItemId(setMealExpItem.getItemId());
                expCtrItemList1.add(expCtrItem);
            }
            //项目的isDelete值进行加一
            int b = expCtrItemService.updateBatch(expCtrItemList1);
            if (b <= 0) {
                System.out.println("********************修改套餐时修改项目isDelete自加一失败********************");
            }
            //先根据套餐id删除关系表中的数据
            SetMealExpItem setMealExpItem = new SetMealExpItem();
            setMealExpItem.setSetMealId(setMeal.getSetMealId());
            int n = setMealService.deleteBySetMealExpItem(setMealExpItem);
            //批量插入关系表
            m = setMealService.insertBatch(setMealExpItemList);
        }
        //修改
        if (m <= 0) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"修改套餐项目失败",m);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"修改成功",m);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }

    //根据套餐id查询套餐信息
    @RequestMapping(value = "/selectById", method = RequestMethod.POST)
    public Wrapper selectById(Integer setMealId) {
        //校验
        if (setMealId == null) {
            //return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"套餐id不能为空",setMealId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("SetMeal.id.null", null));
        }
        SetMeal setMeal = setMealService.selectById(setMealId);
        if (setMeal == null) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"没有此id",setMealId);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("Examine.not.id", null));
        }
        //return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"查询成功",setMeal);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }
    //查询该机构的所有套餐
    @RequestMapping(value = "/showAll", method = RequestMethod.POST)
    public Wrapper showAll(@RequestBody Map<String,Object> queryMap) {
        //校验
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        queryMap.put("homeId",homeId);
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        List<SetMeal> setMealList = setMealService.showAll(queryMap);
        PageInfo<SetMeal> info = new PageInfo<>(setMealList);
        if (CollectionUtils.isEmpty(setMealList)) {
            //return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该社区还未添加任何套餐",null);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"查询成功",info);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null));
    }
}
